﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Reflection;
using Core;

namespace Forums.Models
{
    [MetadataType(typeof(Forum_Validation))]
    public partial class Forum
    {
    }

    public class Forum_Validation
    {
        [HiddenInput(DisplayValue = false)]
        public Guid ForumId { get; set; }

        [HiddenInput(DisplayValue = false)]
        public Guid BusinessUnitId { get; set; }

        [HiddenInput(DisplayValue = false)]
        public Guid ForumHomePageId { get; set; }

        [Required(ErrorMessage = "Forum name is required.")]
        [Display(Name = "Name")]
        [StringLength(127, ErrorMessage = "Forum name cannot be more than 127 characters.")]
        [DataType(DataType.Text)]
        public string ForumName { get; set; }
    }

    public class ForumCreate
    {
        [HiddenInput(DisplayValue = false)]
        public Guid ForumId { get; set; }

        [HiddenInput(DisplayValue = false)]
        public Guid BusinessUnitId { get; set; }

        [HiddenInput(DisplayValue = false)]
        public Guid ParentForumId { get; set; }

        [HiddenInput(DisplayValue = false)]
        public Guid ForumHomePageId { get; set; }

        [Required(ErrorMessage = "Forum/Folder name is required.")]
        [Display(Name = "Forum/Folder Name")]
        [StringLength(127, ErrorMessage = "Forum/Folder name cannot be more than 127 characters.")]
        [DataType(DataType.Text)]
        public string ForumName { get; set; }

        [Required(ErrorMessage = "URL is required.")]
        [Display(Name = "URL")]
        [StringLength(127, ErrorMessage = "URL cannot be more than 127 characters.")]
        public string PageName { get; set; }

        [Display(Name = "Meta Keywords")]
        [StringLength(255, ErrorMessage = "Meta Keywords cannot be more than 255 characters.")]
        [DataType(DataType.MultilineText)]
        public string MetaKeywords { get; set; }

        [Display(Name = "Meta Description")]
        [StringLength(255, ErrorMessage = "Meta description cannot be more than 255 characters.")]
        [DataType(DataType.MultilineText)]
        public string MetaDescription { get; set; }

        [Required(ErrorMessage = "You have to specify if this Forum/Folder is included on Main Menu.")]
        [StringLength(1, ErrorMessage = "Can be only 1 character")]
        [Display(Name = "On Main Menu?")]
        public string OnMainMenuYN { get; set; }

        [Required(ErrorMessage = "You have to specify if this Forum/Folder accepts comments by anonymous users.")]
        [StringLength(1, ErrorMessage = "Can be only 1 character")]
        [Display(Name = "Allow Annoymous Comments?")]
        public string AllowAnonymousCommentsYN { get; set; }

        [Required(ErrorMessage = "You have to select who can view this page.")]
        [Display(Name = "Permission")]
        public Guid PermissionId { get; set; }

        [DataType(DataType.MultilineText)]
        [Display(Name = "Content")]
        [AllowHtml]
        public string ContentText { get; set; }

        public List<Permission> PermissionList 
        {
            get
            {
                ForumEntities fe = new ForumEntities();
                return fe.Permissions.ToList();
            }
        }

        public Guid UserId { get; set; }
        public string UserFullName { get; set; }
        public Guid DomainId { get; set; }

        public ForumCreate() { }

        public ForumCreate(Guid businessunitid, Guid parentforumid)
        {
            ForumEntities fe = new ForumEntities();
            BusinessUnitId = businessunitid;
            ParentForumId = parentforumid;
            OnMainMenuYN = "N";
            AllowAnonymousCommentsYN = "Y";
            PermissionId = fe.Permissions.First(m => m.Name == "Can Use Anonymously").PermissionId;
        }

        public string Save()
        {
            string retval = "";
            try
            {
                ForumEntities fe = new ForumEntities();

                // Create all the Guids to maintain referential integrity
                string forumname = ForumName;
                Guid ForumPageId = Guid.NewGuid();
                Guid PageId = Guid.NewGuid();
                Guid ForumId = Guid.NewGuid();
                Guid PluginId = new Guid(((System.Runtime.InteropServices.GuidAttribute)(Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false)[0])).Value);
                Guid ContainerId = GetContainerId(fe, ForumName, PluginId);

                // Create Forum
                Forums.Models.Forum Forum = new Models.Forum();
                Forum.ForumId = ForumId;
                Forum.BusinessUnitId = BusinessUnitId;
                Forum.Parent = ParentForumId;
                Forum.Name = ForumName;
                Forum.AllowAnonymousCommentsYN = AllowAnonymousCommentsYN;
                Forum.OnMainMenuYN = OnMainMenuYN;
                Forum.ForumHomePageId = ForumPageId;
                Forum.LastActivityDT = DateTime.Now;
                Forum.IsDroppedYN = "N";
                Forum.CreateDT = DateTime.Now;
                Forum.CreatedById = UserId;
                Forum.CreatedByName = UserFullName;
                Forum.ModifiedDT = DateTime.Now;
                Forum.ModifiedById = UserId;
                Forum.ModifiedByName = UserFullName;

                // Create Page
                Forums.Models.Page p = new Page();
                p.PageId = PageId;
                p.BusinessUnitId = BusinessUnitId;
                p.PermissionId = PermissionId;
                p.PageName = PageName;
                p.Title = ForumName;
                p.ShowTitleYN = "N";
                p.MetaKeywords = MetaKeywords;
                p.MetaDescription = MetaDescription;
                p.ContainerId = ContainerId;
                p.OnMainMenuYN = OnMainMenuYN;
                p.IsTemplateYN = "N";
                p.IsDroppedYN = "N";
                p.CreateDT = DateTime.Now;
                p.CreatedById = UserId;
                p.CreatedByName = UserFullName;
                p.ModifiedDT = DateTime.Now;
                p.ModifiedById = UserId;
                p.ModifiedByName = UserFullName;

                // Create Template Overide
                TemplateOveride to = new TemplateOveride();
                to.TemplateOverideId = Guid.NewGuid();
                to.PageId = PageId;
                to.TemplateContentId = PluginId;
                to.OverideContentId = ForumPageId;
                to.IsDroppedYN = "N";
                to.ModifiedDT = DateTime.Now;
                p.TemplateOverides.Add(to);

                // Add the entities to the model and save changes
                fe.AddToForums(Forum);
                fe.SaveChanges();
                fe.AddToPages(p);
                fe.SaveChanges();

                // Create Mainmenu entry if Specified
                if (p.OnMainMenuYN == "Y")
                {
                    Core.Models.MainMenu menu = new Core.Models.MainMenu();
                    menu.MenuItemId = Guid.NewGuid();
                    menu.DomainId = DomainId;
                    menu.Name = p.Title;
                    menu.URL = p.PageName.Substring(1);
                    menu.UserPermission = fe.Permissions.First(m => m.PermissionId == p.PermissionId).Name;
                    menu.Sequence = 1;
                    menu.HideOnSmallDeviceYN = "N";
                    menu.IsDroppedYN = "N";
                    menu.CreateDT = DateTime.Now;
                    menu.CreatedById = UserId;
                    menu.CreatedByName = UserFullName;
                    menu.ModifiedDT = DateTime.Now;
                    menu.ModifiedById = UserId;
                    menu.ModifiedByName = UserFullName;
                    Core.Models.CoreEntities core = new Core.Models.CoreEntities();
                    core.AddToMainMenus(menu);
                    core.SaveChanges();
                }

                // Index the content
                Core.Search.SearchDoc doc = new Core.Search.SearchDoc();
                doc.DocId = p.PageId;
                doc.BusinessUnitId = Guid.Empty; // Search convention is Guid.EWmpty if Domain wide access
                doc.PluginId = PluginId;
                doc.URL = p.PageName.Substring(1);
                doc.Title = p.Title;
                doc.Keywords = p.MetaKeywords;
                doc.Description = p.MetaDescription;
                doc.Content = Core.Tools.GetTextFromHtml(ContentText);
                Core.Search.SearchEngine se = new Core.Search.SearchEngine(DomainId);
                se.IndexContent(doc);
            }
            catch (Exception e)
            {
                retval = Tools.ExceptionMessage(e);
            }
            return retval;
        }

        private Guid GetContainerId(ForumEntities fe, string forumname, Guid pluginid)
        {
            Guid ContainerId = Guid.NewGuid();
            List<Container> clist = fe.Containers.Where(m => (m.ContainerName == "Forum Template Container" && m.PluginId == pluginid && m.IsDroppedYN == "N")).ToList();
            if (clist.Count <= 0)
            {
                // Create Container Entity
                ContainerId = Guid.NewGuid();
                Container container = new Container();
                container.ContainerId = ContainerId;
                container.ContainerType = "C";
                container.ShowChromeYN = "N";
                container.ContainerName = "Forum Template Container";
                container.Title = forumname;
                container.Width = 0;
                container.ParentContainerId = null;
                container.PluginId = pluginid;
                container.ContentId = pluginid;
                container.IsDroppedYN = "N";
                container.CreateDT = DateTime.Now;
                container.CreatedById = UserId;
                container.CreatedByName = UserFullName;
                container.ModifiedDT = DateTime.Now;
                container.ModifiedById = UserId;
                container.ModifiedByName = UserFullName;
                fe.AddToContainers(container);
                fe.SaveChanges();
            }
            else
            {
                ContainerId = clist[0].ContainerId;
            }
            return ContainerId;
        }
    }

    public class ForumPageUI : ForumCreate
    {

        [HiddenInput(DisplayValue = false)]
        public Guid ForumPageId { get; set; }

        [Required(ErrorMessage = "Title is required.")]
        [Display(Name = "Title")]
        [StringLength(127, ErrorMessage = "Title cannot be more than 127 characters.")]
        [DataType(DataType.Text)]
        public string Title { get; set; }
    }
}